package com.lzw.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//定义拦截器1
public class MyInterceptor1 implements HandlerInterceptor {

//请求发送到达服务器前的方法
// 有一个返回值，false被拦截，不能执行,true未被拦截，可以执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器1拦截到的信息");
        //判断是否登录
        //获取访问路径:
        String path = request.getRequestURI();
        //截取路径中的后缀名:
        if (path.lastIndexOf(".") > -1) {
            path = path.substring(path.lastIndexOf("."));
        }
        //判断是否登录:
        //从session作用域中获取登录的用户名:
        String uname = (String) request.getSession().getAttribute("uname");
        //判断uname是否为空:
        if (uname != null || ".jpg".equals(path) || ".png".equals(path) || ".gif".equals(path)) {//已经登录过
            return true;//放行
        }
        //没有登录过:(重定向回登录界面:)
        response.sendRedirect("/index.jsp");
        return false;
    }
    //请求在服务器执行完经过的方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器1处理完毕的信息");
    }

    //请求返回到客户端之后要执行的方法

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器1请求到达客户端后执行的方法");
    }
}
